export class VersionNotifier {
    constructor(url, options = {}) {
        this.url = url;
        this.socket = null;
        this.heartbeatInterval = options.heartbeatInterval || 30000; // 心跳频率，默认30秒
        this.reconnectDelay = options.reconnectDelay || 3000;        // 重连间隔
        this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
        this.reconnectAttempts = 0;
        this.heartbeatTimer = null;
        this.reconnectTimer = null;
        this.onMessageCallback = null;
        this.isManualClose = false;
        this.lastPongTime = Date.now();
        this.version = 1.0


        // 监听网络恢复
        window.addEventListener('online', () => {
            if (!this.socket || this.socket.readyState === WebSocket.CLOSED) {
                console.log('网络恢复，尝试重连...');
                this.reconnect()
            }
        })

        // 监听网络连接质量变化（如 WiFi -> 4G）
        if (navigator.connection && typeof navigator.connection.addEventListener === 'function') {
            navigator.connection.addEventListener('change', () => {
                console.log('📶 网络连接状态变更:', navigator.connection);
                this.adjustHeartbeatInterval();
                if (!this.socket || this.socket.readyState === WebSocket.CLOSED) {
                    console.log('连接已关闭，尝试重连（网络 change）...');
                    this.reconnect();
                }
            })
        }
    }

    connect() {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            console.log('WebSocket已连接')
            return
        }

        this.socket = new WebSocket(this.url)
        this.socket.onopen = () => {
            console.log('WebSocket连接成功')
            this.reconnectAttempts = 0; // ✅ 清零尝试次数
            this.adjustHeartbeatInterval();
            this.startHeartbeat();
        }

        this.socket.onmessage = (event) => {
            console.log('📩 收到消息:', event.data);
            let data = event.data
            if (data !== 'pong') {
                data = JSON.parse(data)
                console.log('lai', data.type === 'version')
                if (data.type === 'version' && data.message !== this.version) {
                    this.version = data.message
                    if (confirm(`新版本 ${this.version} 已发布，是否立即刷新？`)) {
                        window.location.reload();
                    }
                }
                if (this.onMessageCallback) this.onMessageCallback(data);
            } else if (data === 'pong') {
                this.lastPongTime = Date.now();
            }
        }

        this.socket.onclose = () => {
            console.warn('❌ WebSocket连接关闭');
            this.stopHeartbeat();
            if (!this.isManualClose) this.reconnect();
        }

        this.socket.onerror = (error) => {
            console.error('⚠️ WebSocket错误:', error);
            this.socket.close(); // 触发 onclose
        }
    }

    startHeartbeat() {
        this.lastPongTime = Date.now();
        this.stopHeartbeat(); // 防止重复定时器
        this.heartbeatTimer = setInterval(() => {
            if (this.socket.readyState === WebSocket.OPEN) {
                this.socket.send('ping')
                console.log('❤️ 发送心跳 ping');
            }
            // 检查上次 pong 是否超时（例如 60 秒）
            if (Date.now() - this.lastPongTime > 70000) {
                console.warn('心跳超时，尝试重连');
                this.reconnect();
            }
        }, this.heartbeatInterval);
    }

    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer)
            this.heartbeatTimer = null
        }
    }

    adjustHeartbeatInterval() {
        if (!navigator.connection) return;
        const { rtt, downlink } = navigator.connection;
        console.log(`📡 当前网络 rtt: ${rtt}ms, downlink: ${downlink}Mbps`);
        // rtt 表示往返延迟时间（Round Trip Time），单位是毫秒 数值越大，网络越慢
        // downlink 当前估算的下载带宽（单位：Mbps） 数值越小，网络越差
        if (rtt > 500 || downlink < 0.5) {
            console.log('⚠️ 检测到网络较差，延长心跳间隔至 60 秒');
            this.heartbeatInterval = 60000;
        } else {
            console.log('✅ 网络良好，恢复心跳间隔为默认值');
            this.heartbeatInterval = 30000;
        }
        // 如果已连接，需要重启心跳定时器
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.startHeartbeat();
        }
    }


    reconnect() {
        if (!navigator.onLine) {
            console.warn('当前处于离线状态，等待网络恢复后再连接');
            return;
        }

        if (this.reconnectAttempts > this.maxReconnectAttempts) {
            console.warn('🚫 超过最大重连次数');
            return;
        }

        if (this.reconnectTimer) return;

        this.reconnectAttempts++;
        console.log(`🔁 尝试第 ${this.reconnectAttempts} 次重连...`);
        this.reconnectTimer = setTimeout(() => {
            this.connect();
        }, this.reconnectDelay);
    }

    close() {
        this.isManualClose = true
        this.stopHeartbeat();
        if (this.socket) {
            this.socket.close()
        }
        clearTimeout(this.reconnectTimer)
    }

    send(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(typeof message === 'string' ? message : JSON.stringify(message));
        } else {
            console.warn('🚫 WebSocket未连接，无法发送消息');
        }
    }

    onMessage(callback) {
        this.onMessageCallback = callback;
    }

    isOpen() {
        return this.socket && this.socket.readyState === WebSocket.OPEN
    }
  
}